package commonjwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT工具类
 * @author gaofeng
 * @date 2022-07-22
 */
public class JwtUtils {

    /**
     * 过期时间
     */
    private static final long EXPIRE_TIME = 24 * 60 * 60 * 1000 ;

    /**
     * 自定义密钥
     */
    private static final String TOKEN_SECRET = "myDefineSecret3306" ;

    /**
     * 生成token
     */
    public static String createToken(String target) {
        try {
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME) ;
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET) ;
            Map<String, Object> header = new HashMap<>(2);
            header.put("Type", "Jwt") ;
            header.put("alg", "HS256") ;
            return JWT.create().withHeader(header).withClaim("userMap", target).withExpiresAt(date).sign(algorithm);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null ;
    }

    /**
     * 验证token
     */
    public static boolean verifyToken(String token, String userMap) {
        boolean isSuccess = false ;
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET) ;
            JWTVerifier build = JWT.require(algorithm).withClaim("userMap", userMap).build();
            DecodedJWT verify = build.verify(token);
            isSuccess = true ;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isSuccess ;
    }

    /**
     * 获取token里的信息
     */
    public static String getInfoFromToken(String token) {
        try {
            DecodedJWT decode = JWT.decode(token);
            return decode.getClaim("userMap").asString();
        } catch (Exception e) {
            e.printStackTrace();
            return null ;
        }
    }
}
